package org.example.project.controller;

import org.example.project.entity.User;
import org.example.project.service.UserService;
import org.example.project.util.ResponseCode;
import org.example.project.util.ResponseData;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author linky
 */

@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    /**
     * 获取全部用户
     *
     * @return 全部数据
     */
    @GetMapping
    public ResponseData queryAll(){
        return new ResponseData(ResponseCode.success, this.userService.queryAll());
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/getUserById")
    public ResponseData queryById(@RequestParam("id") int id) {
        return new ResponseData(ResponseCode.success, this.userService.queryById(id));
    }

    /**
     * 通过username模糊查询
     * @param name 用户名
     * @return 符合条件的全部数据
     * */
    @GetMapping("/getUserByName")
    public ResponseData queryByName(@RequestParam("name") String name){
        return new ResponseData(ResponseCode.success, this.userService.queryByName(name));
    }

    /**
     * 检验是否注册，名称精确查询
     * @param username 用户名
     * @return 符合条件的单条数据
     * */
    @GetMapping("/isRegister")
    public ResponseData isRegister(@RequestParam("username") String username) {
        return new ResponseData(ResponseCode.success, this.userService.isRegister(username));
    }

    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @return 符合条件的单条数据
     * */
    @GetMapping("/toLogin")
    public ResponseData toLogin(@RequestParam("username") String username, @RequestParam("password") String password) {
        return new ResponseData(ResponseCode.success, this.userService.toLogin(username, password));
    }

    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseData add(@RequestBody User user) {
        return new ResponseData(ResponseCode.success, this.userService.insert(user));
    }

    /**
     * 编辑数据
     *
     * @param user 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseData edit(@RequestBody User user) {
        return new ResponseData(ResponseCode.success, this.userService.update(user));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseData deleteById( @RequestParam("id") int id) {
        return new ResponseData(ResponseCode.success,this.userService.deleteById(id) );
    }
}

